package com.example.base.system.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.base.excetion.GlobalExcetion;
import com.example.base.job.AppJobModelService;
import com.example.base.job.JobModel;
import com.example.base.job.QuarztUtils;
import com.example.base.system.domain.SysJob;
import com.example.base.system.domain.vo.SysJobVo;
import com.example.base.system.mapper.SysJobMapper;
import com.example.base.system.service.SysJobService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 定时任务表 服务实现类
 * </p>
 *
 * @author xiong
 * @since 2024-02-07
 */
@Service
@Transactional
@CacheConfig(cacheNames = "SysJobServiceImpl")
public class SysJobServiceImpl extends ServiceImpl<SysJobMapper, SysJob> implements SysJobService {


    @Autowired
    private QuarztUtils quarztUtils;

    @Autowired
    private AppJobModelService appJobModelService;

    @Override
    public SysJob getById(Serializable id){
        return super.getById(id);
    }


    @Override
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }


    @Override
    public boolean updateById(SysJob sysjob) {
        return super.updateById(sysjob);
    }


    public SysJob saveOrUpdateSysJob(SysJobVo vo) throws GlobalExcetion {
        SysJob sysJob=new SysJob();
        BeanUtils.copyProperties(vo,sysJob);
        JSONArray array=new JSONArray();
        if(vo.getId()!=null){
            SysJob job=super.baseMapper.selectById(vo.getId());
            if(job==null){
                throw new GlobalExcetion(1,"任务不存在");
            }
            JobModel jobModel=quarztUtils.sysJobToJobModel(job);
            quarztUtils.stopQuarzt(jobModel);

            if(!vo.getGroupName().equals(job.getGroupName())){
                SysJob entity=getSysJobByGroupName(vo.getGroupName());
                if(entity!=null){
                    throw new GlobalExcetion(1,"分组名已存在");
                }
            }
            if(StringUtils.isNotBlank(vo.getParams())){
                String[] strings=vo.getParams().split(",");
                array.addAll(Arrays.asList(strings));
            }
            if(StringUtils.isNotBlank(vo.getAppClass())){
                job.setAppClass(vo.getAppClass());
            }
            job.setParams(array.toJSONString());
            job.setGroupName(vo.getGroupName());
            job.setUpdatetime(new Date());
            job.setAppName(vo.getAppName()==null ? "system" : vo.getAppName());
            super.baseMapper.updateById(job);
            jobModel=quarztUtils.sysJobToJobModel(job);
            if("system".equals(vo.getAppName())){
                quarztUtils.startQuarzt(jobModel);
            }else {
                appJobModelService.startJob(jobModel);
            }
        }else {
            SysJob job=getSysJobByGroupName(vo.getGroupName());
            if(job!=null){
                throw new GlobalExcetion(1,"分组名已存在");
            }
            if(StringUtils.isNotBlank(vo.getParams())){
                String[] strings=vo.getParams().split(",");
                array.addAll(Arrays.asList(strings));
            }
            if(StringUtils.isNotBlank(vo.getAppClass())){
                sysJob.setAppClass(vo.getAppClass());
            }
            sysJob.setParams(array.toJSONString());
            sysJob.setStatus("1");
            sysJob.setDeleted(0);
            sysJob.setTigger(vo.getGroupName());
            sysJob.setCreatetime(new Date());
            sysJob.setUpdatetime(new Date());
            sysJob.setAppName(vo.getAppName()==null ? "system" : vo.getAppName());
            super.baseMapper.insert(sysJob);
            JobModel jobModel=quarztUtils.sysJobToJobModel(sysJob);
            if("system".equals(vo.getAppName())){
                quarztUtils.addQuartz(jobModel);
            }else {
                appJobModelService.updateJob(jobModel);
            }
        }
        return sysJob;
    }


    public SysJob updateSysJobById(SysJob sysjob) throws GlobalExcetion{
        super.updateById(sysjob);
        return sysjob;
    }

    @Override
    public SysJob getSysJobByGroupName(String name) throws GlobalExcetion {
        LambdaQueryWrapper<SysJob> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysJob::getGroupName,name);
        SysJob sysJob=this.baseMapper.selectOne(lambdaQueryWrapper);
        return sysJob;
    }

    @Override
    public SysJob execOne(Serializable id) throws GlobalExcetion {
        SysJob sysJob=this.baseMapper.selectById(id);
        if(sysJob==null){
            throw new GlobalExcetion(1,"任务不存在");
        }
        JobModel jobModel=quarztUtils.sysJobToJobModel(sysJob);
        quarztUtils.execOne(jobModel);
        return sysJob;
    }

    @Override
    public List<SysJob> getSysJobAppName(String appName) {
        LambdaQueryWrapper<SysJob> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysJob::getAppName,appName);
        return this.baseMapper.selectList(lambdaQueryWrapper);
    }
}
